<template>
  <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="520px"
      @close="handleClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="user-dialog"
      destroy-on-close
  >
    <!-- 对话框头部 -->
    <template #header="{  titleId, titleClass }">
      <div class="dialog-header">
        <el-icon class="dialog-icon" :class="isEdit ? 'edit-icon' : 'add-icon'">
          <component :is="isEdit ? 'Edit' : 'Plus'" />
        </el-icon>
        <span :id="titleId" :class="titleClass">{{ dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单内容 -->
    <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="90px"
        label-position="right"
        size="default"
        class="user-form"
    >
      <el-form-item label="用户姓名" prop="userName">
        <el-input
            v-model="form.userName"
            placeholder="请输入用户姓名"
            clearable
            :prefix-icon="User"
            maxlength="20"
            show-word-limit
        />
      </el-form-item>

      <el-form-item label="用户角色" prop="role">
        <el-select
            v-model="form.role"
            placeholder="请选择用户角色"
            style="width: 100%"
            :prefix-icon="Trophy"
        >
          <el-option
              label="管理员"
              :value="1"
              class="role-option admin-option"
          >
            <span class="option-content">
              <el-icon><Trophy /></el-icon>
              <span>管理员</span>
            </span>
          </el-option>
          <el-option
              label="普通用户"
              :value="0"
              class="role-option user-option"
          >
            <span class="option-content">
              <el-icon><User /></el-icon>
              <span>普通用户</span>
            </span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="账户状态" prop="status">
        <el-radio-group v-model="form.status" class="status-radio-group">
          <el-radio :label="0" class="status-radio active-radio">
            <span class="radio-content">
              <el-icon class="status-icon active-icon"><Check /></el-icon>
              <span>活跃</span>
            </span>
          </el-radio>
          <el-radio :label="1" class="status-radio frozen-radio">
            <span class="radio-content">
              <el-icon class="status-icon frozen-icon"><Lock /></el-icon>
              <span>冻结</span>
            </span>
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 编辑模式下的操作区域 -->
      <el-form-item v-if="isEdit" class="action-item">
        <el-divider content-position="left">
          <span class="divider-text">账户操作</span>
        </el-divider>
        <el-button
            type="warning"
            :icon="Refresh"
            @click="handleResetPassword"
            :loading="resetting"
            plain
        >
          重置密码
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 对话框底部 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" :icon="Close">
          取消
        </el-button>
        <el-button
            type="primary"
            @click="submitForm"
            :loading="submitting"
            :icon="Check"
        >
          {{ submitting ? '保存中...' : '保存' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  User,
  Trophy,
  Check,
  Lock,
  Refresh,
  Close,

} from '@element-plus/icons-vue';
import { changePassword, insertUser, updateUser } from "@/api/user";

// Props定义
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  user: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
});

// 事件定义
const emit = defineEmits(['update:visible', 'success']);

// 响应式数据
const dialogVisible = ref(props.visible);
const submitting = ref(false);
const resetting = ref(false);
const formRef = ref(null);

// 表单数据
const form = ref({
  id: null,
  userName: '',
  role: null,
  status: 0,
  password: '123456'
});

// 计算属性
const dialogTitle = computed(() => {
  return props.isEdit ? '编辑用户信息' : '新增用户';
});

// 表单验证规则
const rules = {
  userName: [
    { required: true, message: '请输入用户姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度应在2-20个字符之间', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_]+$/, message: '姓名只能包含中文、英文、数字和下划线', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择账户状态', trigger: 'change' }
  ]
};

// 重置表单
const resetForm = () => {
  form.value = {
    id: null,
    userName: '',
    role: null,
    status: 0,
    password: '123456'
  };
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate();
    }
  });
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  try {
    const valid = await formRef.value.validate();
    if (!valid) return;

    submitting.value = true;

    if (props.isEdit) {
      await updateUser(form.value);
      ElMessage.success('用户信息更新成功');
      emit('success', { ...form.value });
    } else {
      await insertUser(form.value);
      ElMessage.success('用户创建成功');
      emit('success');
    }

    emit('update:visible', false);
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error(props.isEdit ? '更新用户失败' : '创建用户失败');
  } finally {
    submitting.value = false;
  }
};

// 重置密码
const handleResetPassword = async () => {
  try {
    await ElMessageBox.confirm(
        '确定要重置该用户的密码吗？密码将重置为默认值 "123456"',
        '重置密码确认',
        {
          confirmButtonText: '确定重置',
          cancelButtonText: '取消',
          type: 'warning',
          distinguishCancelAndClose: true,
          confirmButtonClass: 'el-button--warning'
        }
    );

    resetting.value = true;
    await changePassword(form.value);
    ElMessage.success('密码重置成功，新密码为：123456');
  } catch (error) {
    if (error !== 'cancel' && error !== 'close') {
      console.error('重置密码失败:', error);
      ElMessage.error('重置密码失败，请稍后重试');
    }
  } finally {
    resetting.value = false;
  }
};

// 监听器
watch(() => props.visible, (val) => {
  dialogVisible.value = val;
});

watch(() => props.user, (newUser) => {
  if (props.isEdit && newUser && Object.keys(newUser).length > 0) {
    form.value = { ...newUser };
  } else if (!props.isEdit) {
    resetForm();
  }
}, { immediate: true, deep: true });

watch(dialogVisible, (val) => {
  emit('update:visible', val);
  if (!val) {
    resetForm();
  }
});
</script>

<style scoped>
.user-dialog :deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 12px 32px 4px rgba(0, 0, 0, 0.12);
}

.user-dialog :deep(.el-dialog__header) {
  padding: 20px 24px 16px;
  border-bottom: 1px solid #ebeef5;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
}

.dialog-header {
  display: flex;
  align-items: center;
  gap: 12px;
  font-weight: 600;
  font-size: 16px;
}

.dialog-icon {
  width: 24px;
  height: 24px;
  padding: 4px;
  border-radius: 6px;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
}

.edit-icon {
  color: #f0f9ff;
}

.add-icon {
  color: #f0f9ff;
}

.user-form {
  padding: 24px;
}

.user-form :deep(.el-form-item) {
  margin-bottom: 24px;
}

.user-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #303133;
}

.user-form :deep(.el-input__wrapper) {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.user-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #409eff;
}

.user-form :deep(.el-select .el-input__wrapper) {
  border-radius: 8px;
}

.role-option {
  padding: 8px 12px;
}

.option-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.admin-option .option-content {
  color: #e6a23c;
}

.user-option .option-content {
  color: #909399;
}

.status-radio-group {
  display: flex;
  gap: 24px;
}

.status-radio :deep(.el-radio__label) {
  padding-left: 8px;
}

.radio-content {
  display: flex;
  align-items: center;
  gap: 6px;
}

.status-icon {
  width: 16px;
  height: 16px;
}

.active-icon {
  color: #67c23a;
}

.frozen-icon {
  color: #f56c6c;
}

.action-item {
  margin-top: 32px;
  margin-bottom: 16px;
}

.action-item :deep(.el-divider) {
  margin: 16px 0;
}

.divider-text {
  color: #909399;
  font-size: 13px;
  font-weight: 500;
}

.action-item :deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px 24px;
  border-top: 1px solid #ebeef5;
  background: #fafbfc;
  border-radius: 0 0 12px 12px;
}

.dialog-footer :deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  padding: 12px 24px;
  min-width: 88px;
}

.dialog-footer :deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.dialog-footer :deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.4);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-dialog :deep(.el-dialog) {
    width: 90% !important;
    margin: 5vh auto;
  }

  .status-radio-group {
    flex-direction: column;
    gap: 12px;
  }
}

/* 动画效果 */
.user-dialog :deep(.el-dialog) {
  animation: dialogSlideIn 0.3s ease-out;
}

@keyframes dialogSlideIn {
  from {
    transform: translateY(-20px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

/* 加载状态样式 */
.user-form :deep(.is-loading) {
  position: relative;
}

.user-form :deep(.is-loading::after) {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
}
</style>